//
//  UIImageView+DownloadImage.swift
//  StoreSearch
//
//  Created by cygarm on 15/12/25.
//  Copyright © 2015年 cygarm. All rights reserved.
//

import Foundation
import UIKit

extension UIImageView {
	func loadImageWithURL(url: NSURL) -> NSURLSessionDownloadTask {
		let session = NSURLSession.sharedSession()
		let downloadTask = session.downloadTaskWithURL(url) { [weak self] (url, response, error) -> Void in
			if error == nil && url != nil {
				if let data = NSData(contentsOfURL: url!) {
					if let image = UIImage(data: data) {
						dispatch_async(dispatch_get_main_queue(), { () -> Void in
							/*
								下载完成时,需要判断UIImageView是否依旧存在
							*/
							if let strongSelf = self {
								strongSelf.image = image
							}
						})
					}
				}
			}
		}
		downloadTask.resume()
		return downloadTask
	}
}